<?php
class SDK_Daily 
{
    const _CONST_TB_DEFAULT_ = 'sdk_daily';

    public static function import ($day, $pkgname, $advertise_list)
    {
        try {
	        $day          = strtotime(date("Y-m-d", strtotime($day)));
	        $package_id   = SDK_Packages::package_id ($pkgname);
	        $package_info = SDK_Packages::info ($package_id);
	        $developer_id = Arr::get($package_info, 'developer', 0);
	
	        //
	        // 删除这个应用（开发者的应用）在这一天的所有下载数据
	        //
	        self::remove(array('day' => $day, 'package_id' => $package_id));
	
	        // 
	        // 导入这个应用下载广告的数据
	        //
	        $ctime = DB::expr('unix_timestamp(now())');
	        foreach ($advertise_list as $adsid => $downs)
	        {
	            $price = SDK_Advertise::price ($adsid);
                $downs = (int) $downs;
	
	            self::insert(array(
	                'day' => $day,
	                'developer_id' => $developer_id,
	                'package_id'   => $package_id,
	                'advertise_id' => $adsid,
	                'counts'       => $downs,
	                'real_counts'  => $downs,
	                'price'        => $price,
	                'ctime'        => $ctime,
	            ));
	        }
        }
        catch (Exception $e)
        {
            echo $e->getMessage();
            return FALSE;
        }
    }

    protected static function remove ($where)
    {
        if (empty($where))
            return;

        $query = DB::delete(self::_CONST_TB_DEFAULT_);
        foreach ($where as $key => $val)
            $query->where($key, '=', $val);
        return $query->execute();
    }

    protected static function insert ($row)
    {
        list($insert_id, $rows) = DB::insert(self::_CONST_TB_DEFAULT_)
            ->columns (array_keys($row))
            ->values  (array_values($row))
            ->execute();

        return $insert_id;
    }
}
